<template>
  <ul class="sub-category">
    <li
      v-for="sub in subs"
      :key="sub.id"
      is="router-link"
      to="/list"
      tag="li"
    >
      <img :src="sub.imageUrl" alt="" />
      <span>{{ sub.title }}</span>
    </li>
  </ul>
</template>

<script>
import { getSubCategories } from '@/api/category'
export default {
  name: 'SubCategory',
  data () {
    return {
      subs: []
    }
  },
  beforeRouteEnter (to, from, next) {
    console.log('before route enter:', this)
    next((vm) => {
      console.log('before route enter next 回调:', vm)
      getSubCategories(to.params.id)
        .then(res => {
          console.log(res)
          vm.subs = res
        })
    })
  },
  beforeRouteUpdate (to, from, next) {
    console.log('before route update', this.$route)
    getSubCategories(to.params.id)
      .then(res => {
        console.log(res)
        this.subs = res
      })
    // 注意，一定要调用 next() 向下一步，否则，路由导航会在这儿停止
    next()
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log('before route leave')
    next()
  }
}
</script>

<style lang="scss" scoped>
  .sub-category {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;

    li {
      width: 40%;
      border: 1px solid #eee;
      display: flex;
      flex-direction: column;
      text-align: center;
      margin-bottom: 4px;
      padding: 6px;
      img {
        max-width: 100%;
      }
    }
  }
</style>
